package api_template

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"go-web-template/db_template"
	"go-web-template/domain_template"
	"io"
	"net/http"
	"os"
)

// Browse to http://localhost:8080/users/joe and you should see 'joe' on the page.
func GetUser(c echo.Context) error {
	// User ID from path `users/:id`
	id := c.Param("id")
	resp, err := http.Get("http://httpbin.org/get")
	if err != nil {
		c.Logger().Error(err)
	}
	var bts []byte
	resp.Body.Read(bts)
	print(bts)
	db_template.UserSave()
	return c.String(http.StatusOK, id)
}

// query-param?team=x-men&member=wolverine
func ShowUser(c echo.Context) error {
	// Get team and member from the query string
	team := c.QueryParam("team")
	member := c.QueryParam("member")
	log.Info("data :  team:" + team + ", member:" + member)
	return c.String(http.StatusOK, "team:"+team+", member:"+member)
}

// Form multipart/form-data
func SaveUser(c echo.Context) error {
	// Get name and email
	name := c.FormValue("name")
	email := c.FormValue("email")
	return c.String(http.StatusOK, "name:"+name+", email:"+email)
}

// $ curl -F "name=Joe Smith" -F "avatar=@/path/to/your/avatar.png" http://localhost:8080/save
// <b>Thank you! Joe Smith</b>
func SaveUser2(c echo.Context) error {
	// Get name
	name := c.FormValue("name")
	// Get avatar
	avatar, err := c.FormFile("avatar")
	if err != nil {
		return err
	}

	// Source
	src, err := avatar.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(avatar.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}

	return c.HTML(http.StatusOK, "<b>Thank you! "+name+"</b>")
}

// Form multipart/form-data
// e.POST("/save1", save)
func ReturnJson(c echo.Context) error {
	u := new(domain_template.User)
	if err := c.Bind(u); err != nil {
		return err
	}
	return c.JSON(http.StatusCreated, u)
	// or
	// return c.XML(http.StatusCreated, u)
}
